<?php

namespace app\index\controller;

use app\common\CommonResponse;
use think\Controller;
use think\Request;

/**
 * 公共方法（验证码、上传等）
 */
class Common extends Controller
{

    /** 获取验证码
     * @param Request $request
     * @return \think\response\Json
     */
    public function send_code(Request $request){
        $phone=$request->get("phone");
        if(empty($phone)){
            return json(CommonResponse::error("手机号不能为空"));
        }
        $code=rand(1000,9999);
        session("code",$code);
        $smsConfig=config('sms_config');
        $res = file_get_contents("http://api.smsbao.com/sms?u=" . $smsConfig['username'] . "&p=" . md5($smsConfig['password']) . "&m=" .$phone . "&c=" .$smsConfig['template'].$code);
        if($res==0){
            return  json(CommonResponse::success("短信发送成功",null));
        }
        return json(CommonResponse::error("短信发送失败"));
    }


    /** 文件上传
     * @param Request $request
     * @return CommonResponse
     */
    public function upload(Request $request){
        // 获取表单上传文件 例如上传了001.jpg
        $file = $request->file("image");
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->move( '../public/uploads');
        if($info){
            $downloadFilePath='/uploads/'.$info->getSaveName();
            return CommonResponse::success("success",['url'=>str_replace("\\","/",$downloadFilePath),'filename'=>$file->info['name']]);
        }else{
            // 上传失败获取错误信息
            return CommonResponse::error($file->getError());
        }
    }
}